# -*- coding:utf-8 -*-
"""
抓取天气预报信息，并通过pyfetion发送短信通知
"""

import os
import re
import urllib
import sys
import time
from fetion import *

def getUrlList(url):
    sock = urllib.urlopen(url)
    strhtml = sock.read()
    strhtml = unicode(strhtml, 'gb2312','ignore').encode('utf-8','ignore')
    local_urls = re.findall('''<td><a href="/weather/shanghai/(.*)">''', strhtml)
    local_names = re.findall('''.htm">(.*)</a></td>''',strhtml)
    local_list = []
    for index in range(len(local_urls)):
        local_list.append([local_urls[index], local_names[index]])
    return local_list
   
def getLocalWeather(url, location):
    try:
        # 获取网页源文件
        sock = urllib.urlopen(url)
        strhtml = sock.read()
        strhtml = unicode(strhtml, 'gb2312','ignore').encode('utf-8','ignore')

        # 正则式取温度信息
        Grades = re.findall('''(\d+)℃''', strhtml)

        # 获取天气描述信息
        weathers = re.findall('''<br/>(.*)</td>''',strhtml)

        weather_dict = {}
        step = 0
        for index in range(3):
            day = "%s" % str(int(time.strftime("%d")) + index) 
            list = [weathers[index], Grades[index + step], Grades[index + step + 1]]
            weather_dict[day] = list    
            step = step + 1
            
        return weather_dict
    except:
        return "There is sth wrong with the weather forecast, please inform the author. thx~"

def getWeather(url = "http://qq.ip138.com/weather/shanghai/"):
    local_url_list = getUrlList(url)
    weather_dict = {}
    for local in local_url_list: 
        local_dict = getLocalWeather(url + local[0], local[1])
        weather_dict[local[1]] = local_dict
    return weather_dict
def sendSMS(sms):
    myphone = '18817865153'  # 手机号
    mypwd = 'xxxxx'  # 登录密码
    destphone = ["6248xxxxx", "7007xxxxx", "6945xxxxx"]  # 发送对象飞信号
    # 发送目的地改为飞信号，之前用的手机号做目的地发送，别人的收不到短信

    print "\nwaiting for login fetion..."
    fetion = PyFetion(myphone, mypwd, 'TCP')
    fetion.login(FetionHidden)

    for phone in destphone:
        print "sending to", phone
        fetion.send_sms(sms, phone, True)
        print "OK"

    fetion.logout()
    return True


def main():
    print "getting out the weather code..."
    weather_dict = getWeather()
    for key in weather_dict.keys():
        print key
        for k in weather_dict[key]:
            print k,weather_dict[key][k][0],weather_dict[key][k][1],weather_dict[key][k][2]
    print "Done."


if __name__ == "__main__":
    sys.exit(main())